/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.main.threading;

import com.bm.setting.ServerConfig;
import com.bm.util.MessagePrinter;
import com.bm.util.Util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ssm
 */
public class QueueSyncLocalToWeb implements Runnable {

    private int maksimum_data_per_request;
    private String url;

    public QueueSyncLocalToWeb(int maksimum_data_per_request, String url) {
        this.maksimum_data_per_request = maksimum_data_per_request;
        this.url = url;
    }

    @Override
    public void run() {
        while (true) {
            Connection conn = ServerConfig.getConnection();
            PreparedStatement pst1 = null;
            ResultSet rs = null;
            try {
                int waiting_interval = 15;

                String query = "select * from kamisa.sync_local_to_web where flag = 0 or (flag = -1 and time_created > NOW() + INTERVAL '7 MINUTES') order by id_log limit " + maksimum_data_per_request;
                pst1 = conn.prepareStatement(query);
                rs = pst1.executeQuery();

                JsonArray jsaResp = new JsonArray();
                JsonParser jse = new JsonParser();

                int queue_count = 0;
                String list_id_log = "";
                while (rs.next()) {

                    JsonObject jsoResp = new JsonObject();
                    jsoResp.add("id_log", jse.parse(rs.getString("id_log")));
                    jsoResp.add("query", jse.parse("'" + rs.getString("query") + "'"));
                    jsoResp.add("data", jse.parse("'" + rs.getString("data") + "'"));
                    jsoResp.add("flag", jse.parse(rs.getString("flag")));
                    jsoResp.add("time_created", jse.parse("'" + rs.getString("time_created") + "'"));

                    jsaResp.add(jsoResp);
                    queue_count++;

                    if (list_id_log.equals("")) {
                        list_id_log = rs.getString("id_log");
                    } else {
                        list_id_log += "," + rs.getString("id_log");
                    }

                }

                if (queue_count > 0) {
                    Statement st = conn.createStatement();
                    st.execute("update kamisa.sync_local_to_web set flag = -1 where id_log in (" + list_id_log + ")");

                    String data = Util.doRequestWithTimeout(jsaResp.toString(), url + "/sync_local_to_web", true, 30000, 1);

                    if (data.trim().equalsIgnoreCase("none")) {
                        MessagePrinter.print("Tidak ada transaksi");
                    } else {
                        JsonArray jsa = null;

                        try {
                            jsa = jse.parse(data).getAsJsonArray();
                        } catch (Exception e) {
                            System.out.println("Error Parsing web " + e.getMessage());
                            try {
                                Thread.sleep(15 * 1000);
                            } catch (InterruptedException ex) {
                            }
                            ServerConfig.close(rs);
                            ServerConfig.close(pst1);
                            ServerConfig.close(conn);
                            continue;
                        }

                        for (int i = 0; i < jsa.size(); i++) {
                            waiting_interval--;
                            long id_log = jsa.get(i).getAsLong();
                            MessagePrinter.print("Memproses " + (i + 1) + " dari " + jsa.size() + " data queue flag (id_queue : " + id_log + ")");

                            PreparedStatement pst = null;
                            try {
                                query = "update kamisa.sync_local_to_web set flag = 1 where id_log = ?";
                                pst = conn.prepareStatement(query);
                                pst.setLong(1, id_log);
                                pst.executeUpdate();
                            } catch (SQLException ex) {
                                Logger.getLogger(QueueSyncLocalToWeb.class.getName()).log(Level.SEVERE, null, ex);
                            } finally {
                                ServerConfig.close(pst);
                            }
                        }
                    }
                }
                try {
                    if (waiting_interval <= 0) {
                        ServerConfig.close(rs);
                        ServerConfig.close(pst1);
                        ServerConfig.close(conn);
                    }
                    MessagePrinter.print("Menunggu queue sync_local_to_web berikutnya selama " + waiting_interval + " detik");
                    Thread.sleep(waiting_interval * 1000);
                } catch (InterruptedException ex) {
                    MessagePrinter.printDebug(ex.getMessage());
                }
            } catch (SQLException ex) {
                Logger.getLogger(QueueSyncLocalToWeb.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                ServerConfig.close(rs);
                ServerConfig.close(pst1);
                ServerConfig.close(conn);
            }
        }
    }
}
